import json
import requests
import mysql.connector
from mysql.connector import Error

insert_url = "http://113.31.111.86:19003/knowledge1/insert_data/"
delete_url = "http://113.31.111.86:19003/knowledge1/delete_data/"
get_content_url = "http://113.31.111.86:19003/knowledge1/get_file_content/"

# 数据库配置
db_config = {
    "host": "113.31.111.86",
    "port": 19009,
    "user": "root",
    "password": "UnidteVdfZwfFERW8nZp5@20210628Hz",
    "database": "llm_data_milvus_final",
}

# 创建数据库连接
def db_connection():
    conn = None
    try:
        conn = mysql.connector.connect(**db_config)
    except Error as e:
        print("mysql error:", e)
    return conn


def formal_name(name):
    return name.replace("-", "_").replace("——", "_")


# def insert_file_content(data):
#     if "contents" in data:
#         if data["contents"]:
#             return {"code": 400, "message": "Parameter contents should be list and the content should be not empty!", "data": None}
#         content_list = data["contents"]
#     else:
#         return {"code": 400, "message": "Parameter contents should be given!", "data": None}
    
#     if "fileId" in data and data["fileId"] is not None:
#         file_id_list = [data["fileId"]] * len(question_list)
#     else:
#         return {"code": 400, "message": "Parameter fileId should be given!", "data": None}
#     if "fileName" in data:
#         if data["fileName"] and data["fileName"] == "":
#             return {"code": 400, "message": "Parameter fileName should be string and the content should be not empty!", "data": None}
#         file_name_list = [data["fileName"]] * len(question_list)
#     else:
#         return {"code": 400, "message": "Parameter fileName should be given!", "data": None}
    
    
#     if "thirdGroupId" in data:
#         thirdId = data["thirdGroupId"]
#     else:
#         return {"code": 400, "message": "Parameter thirdGroupId should be given!", "data": None}

#     suffix = "qa"
        
#     cursor.execute("SELECT * FROM table_platform_kgbase WHERE thirdId = %s and status = 1", (thirdId,))
#     rows = cursor.fetchall()
#     if rows:
#         base_name = rows[0][3]
#         thirdParentId = rows[0][6]
#         cursor.execute("SELECT * FROM table_platform_kgbase WHERE thirdId = %s and status = 1", (thirdParentId,))
#         rows = cursor.fetchall()
#         if rows:
#             thirdParentId = rows[0][6]
#             cursor.execute("SELECT * FROM table_platform_kgbase WHERE thirdId = %s and status = 1", (thirdParentId,))
#             rows = cursor.fetchall()
#             if rows:
#                 project_name = rows[0][3]
#             else:
#                 return {"code": 400, "message": "thirdGroupId对应子表不存在上一层级", "data": None}
#         else:
#             return {"code": 400, "message": "thirdGroupId对应子表不存在上一层级", "data": None}
#     else:
#         return {"code": 400, "message": "thirdGroupId对应子表不存在", "data": None}
    
#     question_list = []
#     question_id_list = []
#     for c in content_list:
#         question_list.append(c["content"])
#         question_id_list.append(c["contentId"])
#     insert_data = {
#         "text": json.dumps(question_list),
#         "text_uid": json.dumps(question_id_list),
#         "detail_text": json.dumps(["无"]),
#         "embedding": json.dumps(["m3e-base"]),
#         "meta_data": json.dumps([{}]),
#         "source_id": json.dumps(file_id_list),
#         "source": json.dumps(file_name_list),
#         "project": json.dumps([project_name]),
#         "base": json.dumps([base_name]),
#         "base_type": json.dumps([""]),
#         "comment": "front"
#     }
#     try:
#         res = requests.post(insert_url, data=insert_data)
#         print(res.json())
#     except Exception as e:
#         print("error", e)
#         return {"code": 400, "message": "insert fail!", "data": None}
#     return {"code": 200, "message": "insert success!", "data": None}


def delete_file_content(data, logger):
    if "fileId" in data:
        file_id = data["fileId"]
    else:
        return {"code": 400, "message": "Parameter fileId should be given!", "data": None}

    delete_data = {
        "embedding": "m3e-base",
        "source_id": file_id
    }
    try:
        res = requests.post(delete_url, data=delete_data)
        logger.info("delete results:"+str(res.json()))
    except Exception as e:
        logger.error("error:"+str(e))
        return {"code": 400, "message": "delete fail!", "data": None}
    return {"code": 200, "message": "delete success!", "data": None}


def update_file_content(data, logger):
    if "contents" in data:
        if not data["contents"]:
            return {"code": 400, "message": "Parameter contents should be list and the content should be not empty!", "data": None}
        content_list = data["contents"]
    else:
        return {"code": 400, "message": "Parameter contents should be given!", "data": None}
    
    if "fileId" in data and data["fileId"] is not None:
        file_id = data["fileId"]
    else:
        return {"code": 400, "message": "Parameter fileId should be given!", "data": None}
    if "fileName" in data:
        if data["fileName"] and data["fileName"] == "":
            return {"code": 400, "message": "Parameter fileName should be string and the content should be not empty!", "data": None}
        file_name = data["fileName"]
    else:
        return {"code": 400, "message": "Parameter fileName should be given!", "data": None}
    
    
    if "thirdGroupId" in data:
        thirdId = data["thirdGroupId"]
    else:
        return {"code": 400, "message": "Parameter thirdGroupId should be given!", "data": None}

    conn = db_connection()
    cursor = conn.cursor()
    
    suffix = "qa"
        
    cursor.execute("SELECT * FROM table_platform_kgbase WHERE thirdId = %s and status = 1", (thirdId,))
    rows = cursor.fetchall()
    if rows:
        base_name = formal_name(rows[0][3])
        thirdParentId = rows[0][6]
        cursor.execute("SELECT * FROM table_platform_kgbase WHERE thirdId = %s and status = 1", (thirdParentId,))
        rows = cursor.fetchall()
        if rows:
            thirdParentId = rows[0][6]
            cursor.execute("SELECT * FROM table_platform_kgbase WHERE thirdId = %s and status = 1", (thirdParentId,))
            rows = cursor.fetchall()
            if rows:
                project_name = formal_name(rows[0][3])
            else:
                cursor.close()
                conn.close()
                return {"code": 400, "message": "thirdGroupId对应子表不存在上一层级", "data": None}
        else:
            cursor.close()
            conn.close()
            return {"code": 400, "message": "thirdGroupId对应子表不存在上一层级", "data": None}
    else:
        cursor.close()
        conn.close()
        return {"code": 400, "message": "thirdGroupId对应子表不存在", "data": None}
    
        
    cursor.close()
    conn.close()
    try:
        insert_data = []
        delete_data = []
        # 获取文件对应的内容
        try:
            res = requests.post(get_content_url, data={
                "project_name": project_name,
                "base_name": base_name,
                "source": file_name,
                "source_id": file_id
            })
            print("res", res.json())
        except Exception as e:
            print("res", res.json())
            logger.error("error:"+str(e))
            return {"code": 400, "message": "获取数据失败！", "data": None}
        old_content_list = res.json()["data"]
        new_content_list = content_list
        is_insert = res.json()["insert"]
        if is_insert != 1:
            # 判断text和detail_text改变
            old_text_list = [[c["content"], c["extDocContent"]] for c in old_content_list]
            new_text_list = [[c["content"], c["extDocContent"] if "extDocContent" in c else "无"] for c in new_content_list]
            # 通过内容判断需要新增和删除的条目
            for oc in old_content_list:
                if [oc["content"], oc["extDocContent"]] not in new_text_list:
                    delete_data.append(oc)

            for nc in new_content_list:
                if [nc["content"], nc["extDocContent"] if "extDocContent" in nc else "无"] not in old_text_list:
                    insert_data.append(nc)
            
        else:
            insert_data = new_content_list
            delete_data = []
        
        print("insert num", len(insert_data))
        print("delete num", len(delete_data))
        if delete_data:
            del_uid_list = [d["contentId"] for d in delete_data]

            del_res = requests.post(delete_url, data={
                "question_uid": json.dumps(del_uid_list),
                "project": project_name,
                "base": base_name,
                "embedding": "m3e-base",
                "is_association": "false",
            })
            logger.info("del_res:"+str(del_res.json()))
            
        if insert_data:
            question_list = []
            question_id_list = []
            detail_question_list = []
            for c in content_list:
                question_list.append(c["content"])
                question_id_list.append(c["contentId"])
                detail_question_list.append(c["extDocContent"] if "extDocContent" in c else "无")
            length = len(question_list)
            insert_data = {
                "text": json.dumps(question_list),
                "text_uid": json.dumps(question_id_list),
                "detail_text": json.dumps(detail_question_list),
                "embedding": json.dumps(["m3e-base"]*length),
                "meta_data": json.dumps([{}]*length),
                "source_id": json.dumps([file_id]*length),
                "source": json.dumps([file_name]*length),
                "project": json.dumps([project_name]*length),
                "base": json.dumps([base_name]*length),
                "base_type": json.dumps([""]*length),
                "comment": "front"
            }
            insert_res = requests.post(insert_url, data=insert_data)
            logger.info("insert_res"+str(insert_res.json()))
    except Exception as e:
        logger.error("error:"+str(e))
        return {"code": 400, "message": "update fail!", "data": None}
    return {"code": 200, "message": "update success!", "data": None}